﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BusinessDevelopmentController.cs" company="DissingNellemann">
//   
// All rights reserved </copyright>
// <summary>
//   The business development controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Website.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Website.CRUDServices;
    using Website.Models;
    using Website.Models.Styling;
    using Website.Models.ViewModels;

    using User = Website.Models.Domain.User;

    /// <summary>
    ///     The business development controller.
    /// </summary>
    public class BusinessDevelopmentController : BaseController
    {
        #region Public Methods and Operators

        /// <summary>
        ///     The get header items.
        /// </summary>
        /// <returns>
        ///     The list of headeritems for a business development view.
        /// </returns>
        public static List<TableViewHeaderItem> GetHeaderItems()
        {
            var headerItems = new List<TableViewHeaderItem>();
            var item1 = new TableViewHeaderItem { Text = "Dato", SortableName = "TimeOfActivity", IsSortable = true, };

            var item2 = new TableViewHeaderItem { Text = "Lokation", SortableName = "Location.Name", IsSortable = true };
            var item3 = new TableViewHeaderItem { Text = "Kommentar", SortableName = string.Empty, IsSortable = false };
            var item4 = new TableViewHeaderItem
                            {
                                Text = "Oprettet af", 
                                SortableName = "Creator.Name", 
                                IsSortable = true
                            };
            headerItems.Add(item1);
            headerItems.Add(item2);
            headerItems.Add(item3);
            headerItems.Add(item4);

            return headerItems;
        }

        /// <summary>
        /// The index.
        /// </summary>
        /// <param name="skip">
        /// The skip.
        /// </param>
        /// <param name="take">
        /// The take.
        /// </param>
        /// <param name="ds">
        /// The i ds.
        /// </param>
        /// <param name="orderBy">
        /// The order by.
        /// </param>
        /// <param name="sortAscending">
        /// The sort ascending.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index(int? skip, int? take, List<Guid> ids, string orderBy, bool? sortAscending)
        {
            this.Session["CurrentSubMenuSelection"] = "BusinessDevelopment";

            ListView<Activity> view = null;

            List<TableViewHeaderItem> headerItems = GetHeaderItems();

            CRUDServiceProvider.WithCRUDService(
                client =>
                    {
                        var query = new ActivityQuery();
                        query.Settings = new SearchSettings
                                             {
                                                 SortAscending = sortAscending ?? false, 
                                                 Skip = skip ?? 0, 
                                                 Take = take ?? 20, 
                                                 OrderBy = !string.IsNullOrEmpty(orderBy) ? orderBy : "TimeOfActivity"
                                             };
                        query.HasBusinessDevelopment = true;

                        IResult iRes = client.Query(query);
                        if (iRes != null)
                        {
                            var res = (ActivityResult)iRes;
                            view = new ListView<Activity>(
                                res.List.ToList(),
                                query.Settings.Skip ?? 0,
                                query.Settings.Take ?? 100000, 
                                res.TotalRowCount, 
                                query.Settings.OrderBy,
                                query.Settings.SortAscending ?? true, 
                                headerItems, 
                                "Index");

                            this.ViewData["Users"] =
                                PrimitiveTypes.GetUsersWithIDs(
                                    res.List.Where(x => x.Creator.HasValue).Select(x => x.Creator.Value));
                        }
                    });

            this.ViewData["Locations"] = PrimitiveTypes.GetLocations();

            return View(view);
        }

        /// <summary>
        ///     The new business development.
        /// </summary>
        /// <returns>
        ///     The <see cref="ActionResult" />.
        /// </returns>
        public ActionResult NewBusinessDevelopment()
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            return View();
        }

        /// <summary>
        /// The new business development.
        /// </summary>
        /// <param name="datepicker">
        /// The datepicker.
        /// </param>
        /// <param name="location">
        /// The location.
        /// </param>
        /// <param name="profilesSelect">
        /// The profiles select.
        /// </param>
        /// <param name="ownerProjects">
        /// The owner projects.
        /// </param>
        /// <param name="comments">
        /// The comments.
        /// </param>
        /// <param name="status">
        /// The status.
        /// </param>
        /// <param name="talksSelect">
        /// The talks select.
        /// </param>
        /// <param name="andet">
        /// The andet.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        [HttpPost]
        public ActionResult NewBusinessDevelopment(
            DateTime? datepicker, 
            Guid location, 
            List<Guid> profilesSelect, 
            List<Guid> ownerProjects, 
            string comments, 
            string status, 
            List<Guid> talksSelect, 
            string Andet)
        {
            // finish off BDA part of the Activity
            var bda = new BusinessDevelopmentActivity
                          {
                              AdditionalComments = comments,
                              ID = Guid.NewGuid(),
                              TopicElaboration = Andet,
                              Topics = talksSelect.ToArray()
                          };

            // fill out the superclass
            if (datepicker != null)
            {
                var act = new Activity
                              {
                                  Attendees = (profilesSelect ?? new List<Guid>()).ToArray(),
                                  BDA = bda,
                                  OwnerProjects = ownerProjects.ToArray(),
                                  Commentary = status,
                                  ID = Guid.NewGuid(),
                                  Location = location,
                                  TimeOfActivity = datepicker.Value,
                                  Creator = (this.Session["LoggedInUser"] as User).ID
                              };

                // save it!
                CRUDServiceProvider.WithCRUDService(
                    client =>
                        {
                            var cmd = new CreateActivityCommand { Dto = act };

                            client.ExecuteCommand(cmd);
                        });
            }

            return this.RedirectToAction("Index");
        }

        public ActionResult UpdateBusinessDevelopment(Guid id)
        {
            this.ViewData["CreateLocationActionName"] = "CreateLocationJson";
            this.ViewData["Regions"] = PrimitiveTypes.GetRegions();
            this.ViewData["Projects"] = PrimitiveTypes.GetProjects();
            this.ViewData["DiscussionTopics"] = PrimitiveTypes.GetTopics();
            ProfilesView pv = ProfilesView.GetRelated();
            pv.SortAscending = true;
            pv.Skip = 0;
            pv.Take = 10000;
            pv.Profiles = ProfilesView.GetProfilesList("Name", null, pv);
            this.ViewData["Profiles"] = pv;
            // load object for editing
            var dto = new Activity();
            CRUDServiceProvider.WithCRUDService(
                client =>
                    {
                        var query = new ActivityQuery { Settings = new SearchSettings { IDEquals = id } };

                        var res = client.Query(query) as ActivityResult;
                        if (res != null)
                        {
                            if (res.List.Any())
                            {
                                dto = res.List[0];
                            }
                        }
                    });

            // ensure we have some content
            if (dto != null)
            {
                return View(dto);
            }

            // something buggered up. Better send them back to the index.
            return this.RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult UpdateBusinessDevelopment(
            Guid ID,
            Guid ID2,
            DateTime? datepicker,
            Guid location,
            List<Guid> profilesSelect,
            List<Guid> ownerProjects,
            string comments,
            string status,
            List<Guid> talksSelect,
            string Andet)
        {
            // finish off BDA part of the Activity
            var bda = new BusinessDevelopmentActivity
            {
                AdditionalComments = comments,
                ID = ID2,
                TopicElaboration = Andet,
                Topics = talksSelect.ToArray()
            };

            // fill out the superclass
            if (datepicker != null)
            {
                var act = new Activity
                {
                    Attendees = (profilesSelect ?? new List<Guid>()).ToArray(),
                    BDA = bda,
                    OwnerProjects = ownerProjects.ToArray(),
                    Commentary = status,
                    ID = ID,
                    Location = location,
                    TimeOfActivity = datepicker.Value,
                    Creator = (this.Session["LoggedInUser"] as User).ID
                };

                // save it!
                CRUDServiceProvider.WithCRUDService(
                    client =>
                    {
                        var cmd = new UpdateActivityCommand { Dto = act };

                        client.ExecuteCommand(cmd);
                    });
            }

            return this.RedirectToAction("Index");
        }
      

        #endregion
    }
}